package com.zhuzi.guicollect.jsl;

import com.zhuzi.guicollect.jsl.page.OnlyOnePage;
import com.zhuzi.guicollect.utils.AlertUtils;
import com.zhuzi.guicollect.utils.HttpUtils;
import com.zhuzi.guicollect.utils.UrlConst;
import javafx.geometry.Pos;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @Author: MI
 * @Date: 2021/11/12/0:37
 * @Description: 按照用户主题抓取
 */
public class PeopleTopic {
    public static void getTopic(String name, String path) {
        String userId = getUserId(name);
        if (StringUtils.isBlank(userId)) {
            AlertUtils.showNotifications("提示", "没有获取到用户ID", 5, Pos.CENTER);
            return;
        }
        boolean begin = true;
        int i = 0;
        while (begin) {
            String url = String.format(UrlConst.peopleTopic, userId, i);
            Document parse = Jsoup.parse(HttpUtils.httpGet(url));
            Elements byTag = parse.getElementsByTag("a");
            if (byTag.size() > 0) {
                i++;
                AlertUtils.showNotifications("提示", "获取第" + i + "页码", 5, Pos.BOTTOM_RIGHT);
                for (Element ele : byTag) {
                    AlertUtils.showNotifications("提示", ele.text(), 3, Pos.BOTTOM_RIGHT);
                    String delMsg = GetPage.isDeled(ele.attr("href"));
                    if (StringUtils.isBlank(delMsg)) {
                        new OnlyOnePage().collect(ele.attr("href"), path + "/" + name, true, false);
                    } else {
                        AlertUtils.showNotifications("问题不存在", ele.text(), 3, Pos.BOTTOM_RIGHT);

                    }
                }
            } else {
                begin = false;
            }
        }
        AlertUtils.showNotifications("提示", "完成采集", 5, Pos.BOTTOM_RIGHT);
    }

    private static String getUserId(String name) {
        String peopleMainPageStr = HttpUtils.httpGet(String.format(UrlConst.people, name));
        Elements userEleA = Jsoup.parse(peopleMainPageStr).select(".aw-user-follow-box a");
        if (userEleA.size() > 0) {
            return StringUtils.getDigits(userEleA.get(userEleA.size() - 1).toString());
        }
        return "";

    }
}
